package com.xqkad.myfile;


import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.provider.DocumentFile;
import android.util.Log;

import com.xqkad.myfile.tools.IMsg;
import com.xqkad.myfile.tools.MyFormat;
import com.xqkad.myfile.tools.MyIO;
import com.xqkad.myfile.tools.OpenFile;
import com.xqkad.myfile.tools.StorageList;
import com.xqkad.myfile.ui.ItemData;
import com.xqkad.myfile.ui.MainActivity;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.text.*;


public class MySAF {
    private static final int bufsize = 2048;
    private static String[] storagePaths;
    private static SharedPreferences mPreferences;

    public static String getSdUri(Context context){
        if(mPreferences == null)
            mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return mPreferences.getString("sd","");
    }
    public static String getUpanUri(Context context){
        if(mPreferences == null)
            mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return mPreferences.getString("upan","");
    }

    /**
     * @param what 1 sd 2 upan
     */
    public static void saveUri(Context context, String uri, int what){
        if(mPreferences == null)
            mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = mPreferences.edit();
        if(what == 1)
            editor.putString("sd",uri);
        if(what == 2)
            editor.putString("upan",uri);
        editor.commit();
    }

    public static String[] getStoragePaths(Context context){
        if(storagePaths == null){
            Activity activity = (Activity)context;
            storagePaths = new StorageList(activity).getVolumePaths();
        }
        return storagePaths;
    }

    public static void test(Handler hand){
        Message msg = Message.obtain();
        msg.what = 1;
        msg.arg1 = 37;
        hand.sendMessage(msg);
        if(hand != null) return;
        try {
            Thread.sleep(2000);
            msg.what = 1;
            hand.sendMessage(msg);
        } catch (InterruptedException e) { }
    }

    public static ArrayList<ItemData> openPath(ArrayList<String> pathlist, Context context){

        if(pathlist == null || pathlist.size() == 0)
            return null;
        String str=pathlist.get(0);
        String path=null;
        if(str.equals("内部存储")){
            path = getStoragePaths(context)[0];
        }else if(str.equals("sd卡")){
            //struri = MyIO.readString(storagePaths[0]+"/"+MainActivity.saveDir
                    //+"/"+MainActivity.saveFiles[1]);
            path = getStoragePaths(context)[1];
        }else if(str.equals("U盘")){
            path = getStoragePaths(context)[2];
        }
        //df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        //list = MySAF.openDir(df,false);
        for(int i=1 ; i < pathlist.size(); i++){
            path += "/" + pathlist.get(i);
        }
        return MySAF.openDir(path,false);
    }
    public static ArrayList<ItemData> openDir(String path, boolean onlydir){
        ArrayList<ItemData> list_item = new ArrayList<ItemData>();
        ArrayList<String> list_dir = new ArrayList<String>();
        ArrayList<String> list_file = new ArrayList<String>();
        String[] ds = null;
        String[] fs = null;
        Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
        File readfile = new File(path);
        if(!readfile.exists())
            return null;
        File[] files = readfile.listFiles();
        for(File file : files){
            String name = file.getName();
            char a = name.charAt(0);
            if(a == '.')
                continue;
            if(file.isDirectory()){
                list_dir.add(name);
            }else if(!onlydir){
                list_file.add(name);
            }
        }
        ds = (String[])list_dir.toArray(new String[list_dir.size()]);
        fs = (String[])list_file.toArray(new String[list_file.size()]);
        Arrays.sort(ds,cmp);
        Arrays.sort(fs,cmp);
        for(String s : ds){
            ItemData data = new ItemData();
            data.setImageid(R.mipmap.wenjianjia);
            data.setText(s);
            data.setCheck(false);
            list_item.add(data);
        }
        for(String s : fs){
            ItemData data = new ItemData();
            data.setImageid(getItemImageId(s));
            data.setText(s);
            data.setCheck(false);
            list_item.add(data);
        }
        return list_item;
    }

    public static int getItemImageId(String name){
        int imageid;
        if(MyFormat.checkFormat(name, MyFormat.Images)) {
            imageid = R.mipmap.pic;
        }else if(MyFormat.checkFormat(name, MyFormat.Videos)){
            imageid = R.mipmap.video;
        }else if(MyFormat.checkFormat(name, MyFormat.Audios)){
            imageid = R.mipmap.music;
        }else if(MyFormat.checkFormat(name, MyFormat.WebTexts)){
            imageid = R.mipmap.html;
        }else if(MyFormat.checkFormat(name, MyFormat.Texts)){
            imageid = R.mipmap.text;
        }else if(MyFormat.checkFormat(name, MyFormat.Packages)){
            imageid = R.mipmap.apk;
        }else if(MyFormat.checkFormat(name, MyFormat.Words)){
            imageid = R.mipmap.word;
        }else if(MyFormat.checkFormat(name, MyFormat.Excels)){
            imageid = R.mipmap.excel;
        }else if(MyFormat.checkFormat(name, MyFormat.Pdfs)){
            imageid = R.mipmap.pdf;
        }else if(MyFormat.checkFormat(name, MyFormat.PPTs)){
            imageid = R.mipmap.ppt;
        }else if(MyFormat.checkFormat(name, MyFormat.Rars)){
            imageid = R.mipmap.other;
        }else {
            imageid = R.mipmap.other;
        }
        return imageid;
    }

    public static ArrayList<ItemData> openDir(DocumentFile df, boolean onlydir){
        ArrayList<ItemData> list = new ArrayList<ItemData>();
        for (int i=0;i<33;i++){
            ItemData data = new ItemData();
            data.setImageid(R.mipmap.wenjianjia);
            data.setText("item"+i);
            data.setCheck(false);
            list.add(data);
        }
        return list;
    }

    public static Intent openFile(ArrayList<String> currentPaths, String name, String[] storagePaths){
        return openFile(null, currentPaths, name);
    }

    public static Intent openFile(Context context, ArrayList<String> currentPaths, String name){
        String currentpath="";
        File file = null;
        String str = currentPaths.get(0);
        if(str.equals("内部存储")){
            currentpath = getStoragePaths(context)[0];
        }else if(str.equals("sd卡")){
            currentpath = getStoragePaths(context)[1];
        }else if(str.equals("U盘")){
            currentpath = getStoragePaths(context)[2];
        }
        for(int i=1; i<currentPaths.size(); i++){
            currentpath += "/"+currentPaths.get(i);
        }
        file = new File(currentpath, name);
        return OpenFile.getIntent(context, file);
    }

    public static void newDir(ArrayList<String> currentPaths, Context context){
        boolean isSAF = true;
        String name = "newDir";
        DocumentFile df=null;
        String currentpath="";
        String str = currentPaths.get(0);
        String struri = "";
        if(str.equals("内部存储")){
            currentpath = getStoragePaths(context)[0];
            isSAF = false;
        }else if(str.equals("sd卡")){
            struri = getSdUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }else if(str.equals("U盘")){
            struri = getUpanUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }
        for(int i=1; i<currentPaths.size(); i++){
            if(isSAF)
                df = df.findFile(currentPaths.get(i));
            else
                currentpath += "/"+currentPaths.get(i);
        }

        if(isSAF){
            for(int i=0; i<1024; i++){
                if(i != 0) name = name+i;
                if(df.findFile(name) != null)
                    continue;
                df.createDirectory(name);
                break;
            }
        }else{
            for(int i=0; i<1024; i++){
                if(i != 0) name = name+i;
                File f = new File(currentpath,name);
                if(f.exists())
                    continue;
                f.mkdirs();
                break;
            }
        }
    }

    public static void newFile(ArrayList<String> currentPaths, Context context){
        boolean isSAF = true;
        String name = "newFile";
        DocumentFile df=null;
        String currentpath="";
        String str = currentPaths.get(0);
        String struri = "";
        if(str.equals("内部存储")){
            currentpath = getStoragePaths(context)[0];
            isSAF = false;
        }else if(str.equals("sd卡")){
            struri = getSdUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }else if(str.equals("U盘")){
            struri = getUpanUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }
        for(int i=1; i<currentPaths.size(); i++){
            if(isSAF)
                df = df.findFile(currentPaths.get(i));
            else
                currentpath += "/"+currentPaths.get(i);
        }

        if(isSAF){
            for(int i=0; i<1024; i++){
                if(i != 0) name = name+i;
                if(df.findFile(name) != null)
                    continue;
                df.createFile(null, name);
                break;
            }
        }else{
            for(int i=0; i<1024; i++){
                if(i != 0) name = name+i;
                File f = new File(currentpath,name);
                if(f.exists())
                    continue;
                try {
                    f.createNewFile();
                } catch (IOException e) {}
                break;
            }
        }
    }

    public static String copyOnSAF(String readpath, DocumentFile writeDir, ContentResolver resolver, IMsg imsg){
        String re = "ok";
        File readfile = new File(readpath);
        DocumentFile wf = null;
        OutputStream out = null;
        if(writeDir.findFile(readfile.getName()) != null)
            return "over";
        try {
            if(readfile.isFile()){
                wf = writeDir.createFile(null, readfile.getName());
                out = resolver.openOutputStream(wf.getUri());
                MyIO.copyFile(readpath, out, bufsize, imsg);
            }else if(readfile.isDirectory()){
                File[] fs = readfile.listFiles();
                wf = writeDir.createDirectory(readfile.getName());
                for(File f : fs){
                    if(f.isFile()){
                        out = resolver.openOutputStream(wf.createFile(null, f.getName()).getUri());
                        MyIO.copyFile(f.getPath(), out, bufsize, imsg);
                    }else if(f.isDirectory()){
                        copyOnSAF(f.getPath(), wf, resolver, imsg);
                    }
                }
            }
        }catch (Exception e){
            return "catch";
        }
        return "ok";
    }

    public static void copy(ArrayList<String> currentPaths, ArrayList<String> selectPaths, ArrayList<String> selectNames, Context context, Handler handler) {
        boolean isSAF = true;
        DocumentFile df=null;
        String currentpath="", selectpath="";
        long selectsize = 0;
        String str = currentPaths.get(0);
        String struri = "";
        if(str.equals("内部存储")){
            currentpath = getStoragePaths(context)[0];
            isSAF = false;
        }else if(str.equals("sd卡")){
            //currentpath = storagePaths[1];
            struri = getSdUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }else if(str.equals("U盘")){
            //currentpath = storagePaths[2];
            struri = getUpanUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }
        for(int i=1; i<currentPaths.size(); i++){
            if(isSAF)
                df = df.findFile(currentPaths.get(i));
            else
                currentpath += "/"+currentPaths.get(i);
        }
        str = selectPaths.get(0);
        if(str.equals("内部存储")){
            selectpath = getStoragePaths(context)[0];
        }else if(str.equals("sd卡")){
            selectpath = getStoragePaths(context)[1];
        }else if(str.equals("U盘")){
            selectpath = getStoragePaths(context)[2];
        }
        for(int i=1; i<selectPaths.size(); i++){
            selectpath += "/"+selectPaths.get(i);
        }
        selectsize = MyIO.getSelectSize(selectpath, selectNames);
        MyIMsg imsg = new MyIMsg(handler, selectsize);
        for(String name : selectNames){
            String readpath = selectpath+"/"+name;
            if(isSAF)
                copyOnSAF(readpath, df, context.getContentResolver(), imsg);
            else
                MyIO.copy(readpath, currentpath, 2014, imsg);
        }
        Message msg = Message.obtain();
        msg.what = 1;
        if(handler != null)
            handler.sendMessage(msg);
        //Log.d("mytag", currentpath);
        //Log.d("mytag", selectpath);
        //Log.d("mytag", str+" size "+selectsize);
    }

    public static void rename(ArrayList<String> selectPaths, ArrayList<String> selectNames, Context context, String newName){
        boolean isSAF = true;
        DocumentFile df=null;
        String selectpath="";
        String str = selectPaths.get(0);
        String struri = "";
        if(str.equals("内部存储")){
            selectpath = getStoragePaths(context)[0];
            isSAF = false;
        }else if(str.equals("sd卡")){
            struri = getSdUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }else if(str.equals("U盘")){
            struri = getUpanUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }
        for(int i=1; i<selectPaths.size(); i++){
            if(isSAF)
                df = df.findFile(selectPaths.get(i));
            else
                selectpath += "/"+selectPaths.get(i);
        }
        String name = selectNames.get(0);
        if(isSAF)
            df.findFile(name).renameTo(newName);
        else{
            File file = new File(selectpath, name);
            File dest = new File(selectpath, newName);
            file.renameTo(dest);
        }
    }

    public static void delete(final ArrayList<String> selectPaths, final ArrayList<String> selectNames, final Context context, final Handler handler){
        new Thread(){
            @Override
            public void run() {
                deleteImpl(selectPaths,selectNames, context,handler);
            }
        }.start();
    }

    public static void deleteImpl(ArrayList<String> selectPaths, ArrayList<String> selectNames, Context context, Handler handler){
        boolean isSAF = true;
        DocumentFile df=null;
        String selectpath="";
        long selectsize = 0;
        String str = selectPaths.get(0);
        String struri = "";
        if(str.equals("内部存储")){
            selectpath = getStoragePaths(context)[0];
            isSAF = false;
        }else if(str.equals("sd卡")){
            selectpath = getStoragePaths(context)[1];
            struri = getSdUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }else if(str.equals("U盘")){
            selectpath = getStoragePaths(context)[2];
            struri = getUpanUri(context);
            df = DocumentFile.fromTreeUri(context, Uri.parse(struri));
        }
        for(int i=1; i<selectPaths.size(); i++){
            if(isSAF)
                df = df.findFile(selectPaths.get(i));
            selectpath += "/"+selectPaths.get(i);
        }
        selectsize = MyIO.getSelectSize(selectpath, selectNames);
        MyIMsg imsg = new MyIMsg(handler, selectsize);
        for(String name : selectNames){
            String readpath = selectpath+"/"+name;

            if(isSAF)
                df.findFile(name).delete();
            else
                MyIO.deleteFile(new File(readpath), imsg);
        }
        Message msg = Message.obtain();
        msg.what = 1;
        if(handler != null)
            handler.sendMessage(msg);
    }

    private static String sizeImpl(ArrayList<String> selectPaths, ArrayList<String> selectNames, Context context){
        String selectpath="";
        long selectsize = 0;
        String str = selectPaths.get(0);
        if(str.equals("内部存储")){
            selectpath = getStoragePaths(context)[0];
        }else if(str.equals("sd卡")){
            selectpath = getStoragePaths(context)[1];
        }else if(str.equals("U盘")){
            selectpath = getStoragePaths(context)[2];
        }
        for(int i=1; i<selectPaths.size(); i++){
            selectpath += "/"+selectPaths.get(i);
        }
        selectsize = MyIO.getSelectSize(selectpath, selectNames);
        return MyIO.FormatFileSize(selectsize);
    }

    public static void size(ArrayList<String> selectPaths, ArrayList<String> selectNames, Context context, Handler handler){
        Message msg = Message.obtain();
        String[] ss = new String[2];
        ss[0] = sizeImpl(selectPaths, selectNames, context);
        msg.what = 3;
        ss[1] = "选择了；"+selectNames.size()+"个";
        msg.obj = ss;
        handler.sendMessage(msg);
    }

    private static class MyIMsg implements IMsg{
        Handler hand;
        long selectSize;
        long progressSize;
        public MyIMsg(Handler hand, long selectSize) {
            this.hand = hand;
            this.selectSize = selectSize;
            this.progressSize = 0;
        }

        @Override
        public void sendMsg(int len) {
            progressSize +=len;
            Message msg = Message.obtain();
            msg.arg1 = MyIO.getProportion(progressSize, selectSize);
            msg.what = 2;
            if(hand!=null)
                hand.sendMessage(msg);
        }
    }
}
